package com.fxkj.cloud.drms.infra.persistence.dao;

import com.fxkj.cloud.drms.infra.persistence.po.CommandSettingHistoryPO;
import com.fxkj.common.service.BaseJpaRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;

import java.util.List;
import java.util.UUID;

/**
 * <p>description: </p>
 *
 * @author ww
 * @date 2025-03-25 11:06:40
 */
public interface CommandSettingHistoryJpaRepository extends BaseJpaRepository<CommandSettingHistoryPO> {

    Page<CommandSettingHistoryPO> findAllByDeviceIdAndAttributeTypeAndCreatedTimeGreaterThanEqualAndCreatedTimeLessThanEqualOrderByCreatedTimeDesc(Pageable pageable, UUID deviceId, Integer attributeType, Long createdTimeIsGreaterThan, Long createdTimeIsLessThan);

    Page<CommandSettingHistoryPO> findAllByAttributeTypeAndCreatedTimeGreaterThanEqualAndCreatedTimeLessThanEqualOrderByCreatedTimeDesc(Pageable pageable, Integer attributeType, Long createdTimeIsGreaterThan, Long createdTimeIsLessThan);
    @Query(nativeQuery = true,
            value = "SELECT t.* FROM (" +
                    "  SELECT *, ROW_NUMBER() OVER (PARTITION BY attribute_key ORDER BY created_time DESC) as rn " +
                    "  FROM t_command_setting_history" +
                    "  WHERE attribute_key IN (?2) " +
                    "  AND device_id = ?1" +  // 新增过滤条件
                    ") t WHERE t.rn = 1")
    List<CommandSettingHistoryPO> getLatestCommandSettingHistoryKv(UUID deviceId, List<String> attributeKeys);

}
